<?php

class UserController extends St_Controller_Action_Admin {

    public function indexAction() {
        if (!$this->acl->isAllow("view_user")) {
            die("access deny");
            $this->_redirect("access/deny");
        }
        $sorting = $this->_getParam("sorting", false);
        $type = $this->_getParam("type", false);
        
        switch ($sorting) {
            case 'nickName':
                $sortby = "nickName" . $type;
                break;
            case 'groupID':
                $sortby = "GroupID" . $type;
                break;
            case 'email':
                $sortby = "Email" . $type;
                break;
            case 'createddate':
                $sortby = "CreatedDate" . $type;
                break; 
            case 'active':
                $sortby = "IsActive" . $type;
                break;
            default:
                $sortby = "UserID" . $type;
        }        
        $this->view->isSuperAdmin = $this->isSuperAdmin(); // is supper admin
        $currentuser = $this->_getCurrentUser();

        $schoolObj = St_Registry::getDB();       
        Zend_Loader::loadClass("St_User");
        $userObj = new St_User ();
        $datas = $userObj->fetchAll();
        $this->view->datas = $datas;
        $type = $type == ' DESC' ? ' ASC' : ' DESC';
        $this->view->baselink = St_Registry::getConfig("base_url");
        $this->view->typesorting = $type;
        Zend_Loader::loadClass("Zend_Paginator_Adapter_DbSelect");
        Zend_Loader::loadClass("Zend_Paginator");
        $db = St_Registry::getDB();        
        $select = $db->select()
                    ->from(array('u' => 'user'))
                    ->joinLeft(array('g' => 'group'), 'g.GroupID = u.GroupID', array('GroupName' => 'GroupName'))        
                    ->order($sortby);
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam("page", 1));
        $db = St_Registry::getDB();
        $config = St_Registry::getConfig('display');                
        $paginator->setItemCountPerPage ( $config['numberPerPage'] );                
        $paginator->setPageRange ( $config['pageRange'] );
        $this->view->paginator = $paginator;
        $this->view->currentPage = $this->_getParam("page", 1);
    }

    public function deleteAction() {
        if (!$this->acl->isAllow("delete_user")) {
            $this->_forward("deny", "access");
            return;
        }

        Zend_Loader::loadClass("St_User");
        $userObj = new St_User ();
        $uid = $this->_getParam("uid", false);

        $currentControllerName = St_Registry::getControllerName();
        if ($uid == 1) {
            $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
        } else {
            $userObj->delete($userObj->getAdapter()->quoteInto("UserID = ?", $uid));
            $user = $this->_getCurrentUser();
            $this->logger->log($user['nickName'] . " deletes UserID =" . $uid);
        }
        //redirect to other action
        $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
    }

    public function activeAction() {

        if (!$this->acl->isAllow("active_user")) {
            $this->_forward("deny", "access");
            return;
        }
        Zend_Loader::loadClass("St_User");
        $userObj = new St_User ();
        $uid = $this->_getParam("uid", false);
        $status = $this->_getParam("currentstatus", "nostatus");

        $currentControllerName = St_Registry::getControllerName();
        if ($uid == 1 || $status == "nostatus") {
            $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
        } else {

            $newStatus = ($status == "0") ? "1" : "0";

            $userObj->update(array('IsActive' => $newStatus), $userObj->getAdapter()->quoteInto("UserID = ?", $uid));
            $user = $this->_getCurrentUser();
            if ($newStatus == 1)
                $this->logger->log($user['nickName'] . " actives UserID =" . $uid);
            else
                $this->logger->log($user['nickName'] . " deactives UserID =" . $uid);
        }
        //redirect to other action
        $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
    }

    public function addAction() {

        if (!$this->acl->isAllow("add_user")) {
            $this->_forward("deny", "access");
            return;
        }
        $currentControllerName = St_Registry::getControllerName();
        $canAdd = true;
        $result = false;
        $data = $this->_getParam("data", false);
        if (($this->_getSuperAdminGroupID() == $data['groupID']) && (!$this->isSuperAdmin())) {
            $canAdd = false;
        }

        if ($data) {
            Zend_Loader::loadClass("St_User");
            $userObj = new St_User ();

            if (($data['password'] == "") || ($data['password'] != $data['retypePassword']) || (($data['nickName'] == ""))) {
                $canAdd = false;
            }

            unset($data['retypePassword']);
            $data['password'] = md5($data['password']);
            $data['createdDate'] = time();
            $data['lastUpdated'] = time();
            if ($canAdd) {
                $result = $userObj->insert($data);
            }

            if ($result && $canAdd) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['nickName'] . " adds a new user: " . $data['nickName']);
                $this->view->msg = "Add new user successfully";
            } else {
                $this->view->msg = "Can't add user";
            }
            $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
        }

        // get list of group
        Zend_Loader::loadClass("St_Group");
        $groupObj = new St_Group();
        $groupList = $groupObj->fetchAll()->toArray();
        if (!$this->isSuperAdmin()) {
            $groupList = $groupObj->fetchAll("GroupID <> '{$this->_getSuperAdminGroupID()}'")->toArray();
        }
        $groupList = array_reverse($groupList);
        $this->view->groupList = $groupList;
        $this->view->isSuperAdmin = $this->isSuperAdmin();
    }

    public function editAction() {
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/layouts/default/libs/JQuery/jquery.md5.js');
        $currentControllerName = St_Registry::getControllerName();
        $canAdd = true;
        $result = false;
        $uid = $this->_getParam("uid", false);
        $user = $this->_getCurrentUser();
        if (!$uid) {
            $this->view->userid = $user['UserID'];
            $this->_redirect("user/edit/uid/" . $user['UserID']);
        } else {
            if (!$this->acl->isAllow("edit_user") && $user['UserID'] != $uid) {
                $this->_forward("deny", "access");
                return;
            }
        }
 
        $this->view->dataId = $uid;
        Zend_Loader::loadClass("St_User");
        $siteObj = new St_User();

        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'user'))
                ->joinLeft(array('g' => 'group'), 'g.GroupID = u.groupID', array('GroupName' => 'GroupName'))
                ->where("UserID = '$uid'");
        $arrayRow = $db->fetchRow($select);

        if ($arrayRow) {
            $this->view->data = $arrayRow;
        }

        $data = $this->_getParam("data", false);

        if (($this->_getSuperAdminGroupID() == $data['groupID']) && (!$this->isSuperAdmin())) {
            $canAdd = false;
        }

        if ($data) {
            
            if ($data['nickName'] == "") {
                $canAdd = false;
            }

            if (($data['password'] != "" || $data['RetypePassword'] != "") && ($data['password'] != $data['RetypePassword'])) {
                $canAdd = false;
            }

            if ($data['password'] != "") {
                unset($data['retypePassword']);
                $data['password'] = md5($data['password']);
            } else {
                unset($data['retypePassword']);
                unset($data['password']);
            }
       
            if ($canAdd) {
                $data['lastUpdated'] = time();
                $result = $siteObj->update($data, "UserID = '$uid'");
            }
            
            if ($result) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['nickName'] . " edits UserID=" . $uid);
                $this->view->msg = "Update user successfully";
            } else {
                $this->view->msg = "Can't update user";
            }
            $this->view->data = $data;
            if($uid == $user['UserID']){
                
            }else{
                $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
            }
            
        }

        // get list of group
        Zend_Loader::loadClass("St_Group");
        $groupObj = new St_Group();
        $groupList = $groupObj->fetchAll()->toArray();
        if (!$this->isSuperAdmin()) {
            $groupList = $groupObj->fetchAll("GroupID <> '{$this->_getSuperAdminGroupID()}'")->toArray();
        }
        $groupList = array_reverse($groupList);
        $this->view->groupList = $groupList;

        $this->view->isSuperAdmin = $this->isSuperAdmin();
    }

    public function accountingsettingsAction() {
        $currentControllerName = St_Registry::getControllerName();
        $db = St_Registry::getDB();
        $data = $this->_getParam("data", false);
        if ($data) {
            Zend_Loader::loadClass("St_User");
            $userObj = new St_User ();
            if (!empty($data['UserID'])) {
                if ($userObj->update($data, "UserID = {$data['UserID']}")) {
                    $message = array(
                        'status' => 'success',
                        'message' => 'Save successful'
                    );
                } else {
                    $message = array(
                        'status' => 'error',
                        'message' => 'Save unsuccessful'
                    );
                }
                St_Registry::sendMessage(json_encode($message));
                die;
            }
        }
        $UserID = '';
        if ($this->isSuperAdmin()) {
            $select = $db->select()
                    ->from(array('u' => 'user'))
                    ->where("GroupID != 1");
            $user_list = $db->fetchAll($select);
        } else {
            $user = $this->_getCurrentUser();
            $UserID = $user['UserID'];
        }

        $canAdd = true;
        $result = false;
        $arrayRow = '';
        if ($UserID) {
            $select = $db->select()
                    ->from(array('u' => 'user'))
                    ->where("UserID = '$UserID'");
            $arrayRow = $db->fetchRow($select);
        }
        $baseUrl = St_Registry::getConfig("base_url");

        $this->view->result = $arrayRow;
        $this->view->baseUrl = $baseUrl;
        $this->view->isSuperAdmin = $this->isSuperAdmin();
        $this->view->user_list = $user_list;
        $this->view->user = $user;
    }

    public function getaccountingsettingsinfoAction() {
        $db = St_Registry::getDB();
        $UserID = $this->_getParam("UserID", false);
        $select = $db->select()
                ->from(array('u' => 'user'))
                ->where("UserID = '$UserID'");
        $arrayRow = $db->fetchRow($select);
        echo "{$arrayRow['Currency']}|**|{$arrayRow['VATObligated']}|**|{$arrayRow['VATPercentage']}|**|{$arrayRow['PaymentTerms']}|**|";
        die;
    }

    public function externalaccesssettingAction(){
        $currentControllerName = St_Registry::getControllerName();
        $db = St_Registry::getDB();
        $data = $this->_getParam("data", false);
        if ($data) {
            Zend_Loader::loadClass("St_User");
            $userObj = new St_User ();
            if (!empty($data['UserID'])) {
                if ($userObj->update($data, "UserID = {$data['UserID']}")) {
                    $message = array(
                        'status' => 'success',
                        'message' => 'Save successful'
                    );
                } else {
                    $message = array(
                        'status' => 'error',
                        'message' => 'Save unsuccessful'
                    );
                }
                St_Registry::sendMessage(json_encode($message));
                die;
            }
        }
        $UserID = '';
        if ($this->isSuperAdmin()) {
            $select = $db->select()
                    ->from(array('u' => 'user'))
                    ->where("GroupID != 1");
            $user_list = $db->fetchAll($select);
        } else {
            $user = $this->_getCurrentUser();
            $UserID = $user['UserID'];
        }

        $canAdd = true;
        $result = false;
        $arrayRow = '';
        if(empty($UserID)){
            $UserID = $this->_getParam("UserID", false);
        }
        $getInfo = $this->_getParam("getInfo", false);
        if ($UserID) {
            $select = $db->select()
                    ->from(array('u' => 'user'))
                    ->where("UserID = '$UserID'");
            $arrayRow = $db->fetchRow($select);
            if($getInfo){
                echo "{$arrayRow['ExternalBrowserTitle']}|**|{$arrayRow['ExternalPageText']}|**|{$arrayRow['ExternalReportText']}";
                die;
            }
        }
        $baseUrl = St_Registry::getConfig("base_url");

        $this->view->result = $arrayRow;
        $this->view->baseUrl = $baseUrl;
        $this->view->isSuperAdmin = $this->isSuperAdmin();
        $this->view->user_list = $user_list;
        $this->view->user = $user;
    }
    
}

